package com.ruoyi.learn.java.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

@Slf4j
public class CustomThreadPool {
    public static void main(String[] args) {
        // 核心参数：核心线程数2，最大线程数4，空闲超时30s，队列容量10
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2,  // corePoolSize
                4,  // maximumPoolSize
                30, // keepAliveTime
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10),  // 有界队列
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy()  // 拒绝策略
        );

        // 提交15个任务（2核心 + 10队列 + 2非核心 = 14，第15个触发拒绝策略）
        for (int i = 0; i < 150; i++) {
            int taskId = i;
            executor.submit(() -> {
                System.out.println("任务" + taskId + "执行，线程：" + Thread.currentThread().getName());
                log.info("任务" + taskId + "执行，线程：" + Thread.currentThread().getName());
                log.info(executor.toString());
                log.info("executor.getQueue().toString()={}",executor.getQueue().size());
                try { Thread.sleep(1000); } catch (InterruptedException e) {}
            });
        }

        executor.shutdown(); // 关闭线程池
    }
}